<template>
  <div class="image-processor">
    <el-upload :show-file-list="false" :before-upload="handleUpload" accept="image/*">
      <el-button type="primary">上传图片</el-button>
    </el-upload>

    <canvas ref="canvasRef" :width="canvasSize.width" :height="canvasSize.height" class="canvas" />

    <el-button type="success" @click="downloadImage" :disabled="!imageLoaded" class="download-btn">
      下载处理后的图片
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElUpload, ElButton } from 'element-plus'
import { canvasRGB } from 'stackblur-canvas'
const canvasRef = ref<HTMLCanvasElement | null>(null)
const canvasSize = reactive({ width: 800, height: 600 })
const imageLoaded = ref(false)

const handleUpload = async (file: File) => {
  const reader = new FileReader()
  reader.onload = async () => {
    const img = new Image()
    img.src = reader.result as string
    img.onload = () => {
      drawImage(img)
      imageLoaded.value = true
    }
  }
  reader.readAsDataURL(file)
  return false // 阻止 el-upload 默认上传行为
}

const drawImage = (img: HTMLImageElement) => {
  const canvas = canvasRef.value
  if (!canvas) return

  const ctx = canvas.getContext('2d')
  if (!ctx) return

  canvasSize.width = 800
  canvasSize.height = 600

  ctx.clearRect(0, 0, canvas.width, canvas.height)

  ctx.drawImage(img, 0, 0, canvas.width, canvas.height)

  // 使用正确导入的 blur 函数
  canvasRGB(canvas, 0, 0, canvas.width, canvas.height, 20)

  const ratio = Math.min(canvas.width / img.width, canvas.height / img.height, 1)
  const imgWidth = img.width * ratio
  const imgHeight = img.height * ratio
  const x = (canvas.width - imgWidth) / 2
  const y = (canvas.height - imgHeight) / 2

  ctx.drawImage(img, x, y, imgWidth, imgHeight)
}

const downloadImage = () => {
  const canvas = canvasRef.value
  if (!canvas) return
  const link = document.createElement('a')
  link.href = canvas.toDataURL('image/png')
  link.download = 'processed-image.png'
  link.click()
}
</script>

<style scoped>
.image-processor {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding: 20px;
}

.canvas {
  border: 1px solid #ccc;
}

.download-btn {
  margin-top: 10px;
}
</style>
